package com.ideaaedi.shardingdynamictable.config.mybatisplus;

import com.baomidou.mybatisplus.annotation.DbType;
import com.baomidou.mybatisplus.core.handlers.MetaObjectHandler;
import com.baomidou.mybatisplus.extension.plugins.MybatisPlusInterceptor;
import com.baomidou.mybatisplus.extension.plugins.inner.PaginationInnerInterceptor;
import lombok.extern.slf4j.Slf4j;
import org.apache.ibatis.reflection.MetaObject;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.context.annotation.EnableAspectJAutoProxy;
import org.springframework.lang.Nullable;
import org.springframework.stereotype.Component;

import java.time.LocalDateTime;

/**
 * mybatis-plus 配置
 *
 * @author JustryDeng
 * @since 1.0.0
 */
@Slf4j
@Configuration
@EnableAspectJAutoProxy
public class MybatisPlusConfig {
    
    /**
     * 插件配置
     */
    @Bean
    public MybatisPlusInterceptor mybatisPlusInterceptor() {
        MybatisPlusInterceptor interceptor = new MybatisPlusInterceptor();
        // 分页插件
        interceptor.addInnerInterceptor(new PaginationInnerInterceptor(DbType.MYSQL));
        return interceptor;
    }
    
    /**
     * 设置字段自动填充 <br /> <br />
     * <a href="https://baomidou.com/pages/4c6bcf/">官网</a>
     *
     * @author JustryDeng
     * @since 1.0.0
     */
    @Slf4j
    @Component
    public static class MybatisPlusMetaObjectHandler implements MetaObjectHandler {
        
        @Autowired(required = false)
        @SuppressWarnings("SpringJavaAutowiredFieldsWarningInspection")
        OperatorIdProvider operatorIdProvider;
        
        @Override
        public void insertFill(MetaObject metaObject) {
            Long userId = operatorIdProvider == null ? null : operatorIdProvider.operatorId(metaObject);
            // 这里是PO的字段名而不是表的列名
            this.strictInsertFill(metaObject, "createdBy", Long.class, userId);
            this.strictInsertFill(metaObject, "createdAt", LocalDateTime.class, LocalDateTime.now());
        }
        
        @Override
        public void updateFill(MetaObject metaObject) {
            Long userId = operatorIdProvider == null ? null : operatorIdProvider.operatorId(metaObject);
            // 这里是PO的字段名而不是表的列名
            this.strictUpdateFill(metaObject, "updatedBy", Long.class, userId);
            this.strictUpdateFill(metaObject, "updatedAt", LocalDateTime.class, LocalDateTime.now());
        }
        
        /**
         * 数据操作人id提供器
         *
         * @author JustryDeng
         * @since 1.0.0
         */
        public interface OperatorIdProvider {
            
            /**
             * 获取数据操作人id
             *
             * @param metaObject
             *         当前mybatis sql操作元数据
             *
             * @return 数据操作人id
             */
            @Nullable
            Long operatorId(MetaObject metaObject);
        }
    }
}
